package ups.MapParse;

import ups.Common.DataImporter;
import ups.Common.Ship;
import ups.Database.ShipDatabase;
import java.io.File;
import java.util.ArrayList;

public class MapParse extends DataImporter {
	private static String fileNameKey 		= "--file";
	private static String fileNameListKey 	= "--fileList";
	
	private static String hintFileKey 			= "MapParseHintFile";
	private static String letterDirectoryKey 	= "MapParseLetterDirectory";
	private static String offsetFileKey 		= "MapParseOffsetFile";

	public static void main(String[] args) {
		
		for( String s : args ) {
			System.out.println( s );
		}
		
		MapParse parser = new MapParse( args );
		
		//System.setOut( new DebugPrintStream( System.out , false ));
		
		String [] fileNames = null;
		/* Expect either --files or --fileList */
		if( parser.getArgumentForKey( fileNameKey ) != null ) {
			fileNames = new String[1];
			fileNames[0] = parser.getArgumentForKey( fileNameKey );
		} else if( parser.getArgumentForKey( fileNameListKey ) != null ) {
			fileNames = parser.stringsFromFile( new File( parser.getArgumentForKey( fileNameListKey )), "\n");

			for( String k : fileNames ) {
				System.out.println( k );
			}
		} else if( parser.getArgumentForKey("--folder") != null ) {
			File folder = new File( parser.getArgumentForKey("--folder"));
			
			File[] files = folder.listFiles();
			
			fileNames = new String[ files.length ];
			
			int index;
			for( index = 0; index < files.length; index++ ) {
				fileNames[ index ] = files[ index ].getPath();
			}
			
		} else {
			System.err.println( "Neither file or file list specified");
			System.exit(-1);
		}
		System.out.println( parser.getPreferenceForKey( "MapParseLetterDirectory") );
		ShipManager manager = new ShipManager( fileNames, 
											   parser.getPreferenceForKey( hintFileKey ),
											   parser.getPreferenceForKey( letterDirectoryKey ),
											   parser.getPreferenceForKey( offsetFileKey ),
											   null);
											
		ArrayList<Ship> ships = manager.getShips();
		
		/* Check if we should save this or just print it */
		if( parser.getArgumentForKey( "--store" ) != null && parser.getArgumentForKey( "--store" ).equals( "YES")) {
			ShipDatabase db = new ShipDatabase( DBHostName, DBPort, DBName, DBUsername, DBPass );
			for( Ship ship : ships ) {
				System.out.println( ship.toString() );
				db.putShipLocation( ship, ship.getDate() );
			}
		} else {
			for( Ship ship : ships ) {
				System.out.println( ship.toString() );
			}
		}
		
		
	}
	public MapParse( String[] args ) {
		super( args );
	}
}